//
//  NetWorkTool.m
//  chargeAPP
//
//  Created by admin on 2017/4/1.
//  Copyright © 2017年 CarCharge. All rights reserved.
//

#import "NetWorkTool.h"
#import "NetWorkModel.h"
#import "LoginViewController.h"
#import "BaseNavigationViewController.h"

@interface NetWorkTool()
@property (nonatomic,strong)NSURLSessionDataTask *req;
//@property (nonatomic,strong)NSMutableArray *taskArray;
@property (nonatomic,assign)BOOL isHidden;
@end

@implementation NetWorkTool

static NetWorkTool * _instancetype = nil;
- (NSMutableArray *)taskArray
{
    if (!_taskArray) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

+ (instancetype)sharedNetworkTool{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instancetype = [[NetWorkTool alloc] init];
        NSURL *Baseurl = [NSURL URLWithString:kBASE_SERVERADDRS];
        _instancetype = [_instancetype initWithBaseURL:Baseurl];
    });
    _instancetype.responseSerializer = [AFJSONResponseSerializer serializer];
    _instancetype.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];

    return _instancetype;
}
                  
-(void)requestWithUrlString:(NSString *)urlStr
                  method:(NSString *)method
                  parameters:(NSDictionary *)parameters
                   progress:(void(^)(NSProgress * _Nonnull uploadProgress))progress
                  success:(void (^)(id _Nullable))success
                  failure:(void (^)(NSError * _Nonnull))failure
                  {
                      _isHidden = YES;
                      [self getInternetStatue];
                      if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISLOGIN"]) {
                          [self loadCookies];
                      }
                      
                NSLog(@"%@--%@",urlStr,parameters);
                      
                 NSURLSessionDataTask *taskLoad = [self POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
                          if (uploadProgress) {
                              progress(uploadProgress);
                          }
                      } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                          [SVProgressHUD dismiss];
                          NSLog(@"%@----%@",task.currentRequest,responseObject);
                          NSDictionary *dict = [self processDictionaryIsNSNull:responseObject];
                          if ([dict[@"state"] integerValue] == 401) {
                              [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"ISLOGIN"];
                              LoginViewController *LoginVC = [LoginViewController new];
                              LoginVC.msg = dict[@"msg"];
                              BaseNavigationViewController *navc = [[BaseNavigationViewController alloc] initWithRootViewController:LoginVC];
                              [[[UIApplication sharedApplication]delegate]window].rootViewController = navc;
                              [[[[UIApplication sharedApplication]delegate]window] makeKeyAndVisible];
                              NSLog(@"Log out needed");
                          }
                          if (![[NSUserDefaults standardUserDefaults] boolForKey:@"ISLOGIN"]) {
                              [self saveCookies];
                          }
                          if (success) {
                              success(dict);
                          }
                          NetWorkModel *model = [NetWorkModel new];
                          model.urlStr = urlStr;
                          model.task = taskLoad;
                          model.parameters = parameters;
                          for (int i=0; i<self.taskArray.count; i++) {
                              NetWorkModel *tempModel = self.taskArray[i];
                              if ([tempModel.urlStr isEqualToString:urlStr]) {
                                  [self.taskArray removeObject:tempModel];
                              }
                          }
                          
                      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                          NSString *errorStr = [NSString stringWithFormat:@"%ld",error.code];
                          if ([errorStr isEqualToString:@"-999"]) {
                              
                          }else{
                              if (failure) {
                                  failure(error);
                              }
                              NetWorkModel *model = [NetWorkModel new];
                              model.urlStr = urlStr;
                              model.task = taskLoad;
                              model.parameters = parameters;
                              for (int i=0; i<self.taskArray.count; i++) {
                                  NetWorkModel *tempModel = self.taskArray[i];
                                  if ([tempModel.urlStr isEqualToString:urlStr]) {
                                      [self.taskArray removeObject:tempModel];
                                  }
                              }
                          }
                      }];
                      
                      NetWorkModel *model = [NetWorkModel new];
                      model.urlStr = urlStr;
                      model.task = taskLoad;
                      model.parameters = parameters;
                      BOOL isAdd = YES;
                      
                      for (int i=0; i<self.taskArray.count; i++) {
                         NetWorkModel *tempModel = self.taskArray[i];
                          if ([tempModel.urlStr isEqualToString:urlStr]&&[tempModel.parameters isEqualToDictionary:parameters]) {
                              isAdd = NO;
                              [model.task cancel];
                          }
                          if ([tempModel.urlStr isEqualToString:urlStr]&&![tempModel.parameters isEqualToDictionary:parameters]) {
                              [tempModel.task cancel];
                              [self.taskArray removeObject:tempModel];
                              isAdd = YES;
                          }
                      }
                      if (isAdd) {
                          [self.taskArray addObject:model];
                      }
}


// 保存Cookie
- (void)saveCookies
{
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:cookiesData forKey:@"org.skyfox.cookie"];
    [defaults synchronize];
}
//加载Cookie
- (void)loadCookies
{
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"org.skyfox.cookie"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in cookies)
    {
        [cookieStorage setCookie:cookie];
    }
}
//替换null为空
- (id) processDictionaryIsNSNull:(id)obj{
    const NSString *blank = @"";
    
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *dt = [(NSMutableDictionary*)obj mutableCopy];
        for(NSString *key in [dt allKeys]) {
            id object = [dt objectForKey:key];
            if([object isKindOfClass:[NSNull class]]) {
                [dt setObject:blank
                       forKey:key];
            }
            else if ([object isKindOfClass:[NSString class]]){
                NSString *strobj = (NSString*)object;
                if ([strobj isEqualToString:@"<null>"]) {
                    [dt setObject:blank
                           forKey:key];
                }
            }
            else if ([object isKindOfClass:[NSArray class]]){
                NSArray *da = (NSArray*)object;
                da = [self processDictionaryIsNSNull:da];
                [dt setObject:da
                       forKey:key];
            }
            else if ([object isKindOfClass:[NSDictionary class]]){
                NSDictionary *ddc = (NSDictionary*)object;
                ddc = [self processDictionaryIsNSNull:object];
                [dt setObject:ddc forKey:key];
            }
        }
        return [dt copy];
    }
    else if ([obj isKindOfClass:[NSArray class]]){
        NSMutableArray *da = [(NSMutableArray*)obj mutableCopy];
        for (int i=0; i<[da count]; i++) {
            NSDictionary *dc = [obj objectAtIndex:i];
            dc = [self processDictionaryIsNSNull:dc];
            [da replaceObjectAtIndex:i withObject:dc];
        }
        return [da copy];
    }
    else{
        return obj;
    }
}



-(void)getInternetStatue{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了,就会调用这个block
        switch (status) {
            caseAFNetworkReachabilityStatusUnknown://未知网络
                NSLog(@"未知网络");
                break;
                
            caseAFNetworkReachabilityStatusNotReachable://没有网络(断网)
                NSLog(@"没有网络(断网)");
                break;
                
            caseAFNetworkReachabilityStatusReachableViaWWAN://手机自带网络
                NSLog(@"手机自带网络");
                break;
                
            caseAFNetworkReachabilityStatusReachableViaWiFi:// WIFI
                NSLog(@"WIFI");
                break;
        }
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status ==AFNetworkReachabilityStatusReachableViaWiFi)
        {
//            self.wifiStatue=@"有网络";
            NSLog(@"有网");
        }else
        {
//            self.wifiStatue=@"没网络";
            NSLog(@"没有网");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络失去连接" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil,nil];
            alert.delegate =self;
            [alert show];
        }
        
    }];
    // 3.开始监控
    [mgr startMonitoring];
    
}


@end
